define('apps/common/Suggestion', ['core/jQuery', 'core/JSON', 'core/Cache', 'core/ajax/Request'], function(require) {
    
    var $ = require('core/jQuery'),
        Cache = require('core/Cache'),
        JSON = require('core/JSON'),
        Request = require('core/ajax/Request'),
        mix = K.mix,
        
        idPrefix = 'suggestion',
        genID = 0;
        
    function Suggestion(opts) {
        
        // Suggestion id
        var id = idPrefix+'_'+(genID++);
        this.id = id;
        
        // Suggestion URL
        this.URL = null;
        
        // 缓存suggestion数目
        this.cacheSize = 100;
        
        // 多长时间间隔内不再反复请求
        this.interval = 200;
        
        this.sugTimer = null;
        
        mix(this, opts);
        
        this.init();
    }
    
    Suggestion.prototype = {
        
        'init' : function() {
            if(!this.URL) {
                K.log('miss url for suggestion:' + this.id);
                return;
            }
            this.cache = new Cache(this.cacheSize);
        },
        
        /**
         * 获取key对应的suggestion value
         */
        'getSuggestion' : function(param, callback) {
            var cacheData = this.cache.get(JSON.stringify(param));
            
            callback = typeof callback === 'function' ? callback : $.noop;
            
            // 清除等待中的请求
            this.stop();
            
            if(cacheData) {
                callback(cacheData);
            } else {
                this._getXHRData(param, callback);
            }
        },
        
        /**
         * 停止正在进行中的请求或等待队列
         */
        'stop' : function() {
        	clearTimeout(this.sugTimer);
            this.sugXHR && this.sugXHR.abort();
        },
        
        /**
         * 异步获取suggestion value
         */
        '_getXHRData' : function(param, callback) {
            var _this = this, result, sugXHR = this.sugXHR;

            this.sugTimer = setTimeout(function() {
                _this.sugXHR = _this.xhr(param, callback);
            }, this.interval);
        },
        
        /**
         * xhr 请求
         */
        'xhr' : function(param, callback) {
        	var _this = this;
        	return new Request(this.URL)
        		.setData(param)
        		.setHandler(function(data) {
        			_this.cache.put(JSON.stringify(param), data);
                    callback(data);
        		})
        		.setErrorHandler(function(error) {
                    K.log('Data Err:',error);
        		})
        		.send();
        }
    };
    
    return Suggestion;
    
});
